import { Input } from "@/components/ui/input";
import { Loader2 } from "lucide-react";
import { useCaptcha, useRefreshCaptcha } from '@/hooks/use-captcha';
import { useEffect } from 'react';

interface CaptchaInputProps extends React.ComponentProps<"input"> {
  onCaptchaIdChange?: (captchaId: string) => void;
}

export default function CaptchaInput({
  onCaptchaIdChange,
  ...props
}: CaptchaInputProps) {
  // 使用 React Query 获取验证码
  const { data: captchaData, isLoading } = useCaptcha();
  const { mutate: refreshCaptcha } = useRefreshCaptcha();

  // 当验证码数据变化时通知父组件
  useEffect(() => {
    if (captchaData?.captcha_id && onCaptchaIdChange) {
      onCaptchaIdChange(captchaData.captcha_id);
    }
  }, [captchaData?.captcha_id, onCaptchaIdChange]);

  // 刷新验证码
  const handleRefresh = () => {
    refreshCaptcha();
  };

  return (
    <div className="space-y-2">
      <div className="flex gap-2">
        <Input
          className="flex-1"
          {...props}
        />
        <div className="flex items-center gap-1">
          <div className="h-10 w-20 border rounded flex items-center justify-center">
            {isLoading ? (
              <Loader2 className="h-6 w-6 animate-spin text-gray-500" />
            ) : captchaData?.captcha_data ? (
              <img 
                src={captchaData.captcha_data}
                alt="Captcha Code"
                className="h-full w-full cursor-pointer"
                onClick={handleRefresh}
              />
            ) : (
              <div className="text-gray-400 text-xs">Loading...</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
